package subject1.flowchartSys;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author Administrator
 * @Date 2022/12/19--0:33
 * @Description 流程图管理系统
 */
public class FlowchartSys {
    private Set<Integer> middleNodeIdSet = new HashSet<>(); // 中继节点
    private Set<Integer> nodeIdSet = new HashSet<>(); // 普通节点
    private Map<Integer, int[]> connectionMap = new HashMap<>(); // 人工添加的线

    public FlowchartSys() {
    }

    public boolean addNode(int nodeId, int nodeType) {
        return nodeType == 1 ? middleNodeIdSet.add(nodeId) : nodeIdSet.add(nodeId);
    }

    public boolean addConnection(int connectId, int startNodeId, int endNodeId) {
        // 开始id和结束id相等，开始节点不存在，结束节点不存在，连接线已存在，插入失败
        if (startNodeId == endNodeId ||
            (!middleNodeIdSet.contains(startNodeId) && !nodeIdSet.contains(startNodeId)) ||
            (!middleNodeIdSet.contains(endNodeId) && !nodeIdSet.contains(endNodeId)) ||
            connectionMap.containsKey(connectId)) {
            return false;
        }
        connectionMap.put(connectId, new int[]{startNodeId, endNodeId});
        return true;
    }

    public boolean removeConnection(int connectId) {
        return connectionMap.remove(connectId) != null;
    }

    public boolean removeNode(int nodeId) {
        connectionMap.entrySet().removeIf(entry -> {
            int[] startEnd = entry.getValue();
            return startEnd[0] == nodeId || startEnd[1] == nodeId;
        });
        return middleNodeIdSet.remove(nodeId) || nodeIdSet.remove(nodeId);
    }

    public int[] query(int nodeId) {
        if (!middleNodeIdSet.contains(nodeId) && !nodeIdSet.contains(nodeId)) {
            return new int[0];
        };

        // 将线中起始节点ID为nodeId的节点找出来，然后取出结束节点
        List<Integer> endIds = connectionMap.values().stream().filter(arr -> arr[0] == nodeId).mapToInt(arr -> arr[1]).boxed().collect(Collectors.toList());

        // 编号为nodeId的节点应该会连着所有中继节点，所以把所有的中继节点加进来
        endIds.addAll(middleNodeIdSet);

        // 如果自身是中继节点，需要移除自身
        endIds.remove((Integer) nodeId);
        Collections.sort(endIds);
        return endIds.stream().mapToInt(Integer::intValue).toArray();
    }

    public static void main(String[] args) {
        FlowchartSys flowchartSys = new FlowchartSys();
        System.out.println(flowchartSys.addNode(100, 0));
        System.out.println(flowchartSys.addNode(101, 1));
        System.out.println(flowchartSys.addNode(102, 1));
        System.out.println(flowchartSys.addNode(103, 0));
        System.out.println(flowchartSys.addConnection(1001, 101, 103));
        System.out.println(Arrays.toString(flowchartSys.query(101)));
        System.out.println(flowchartSys.removeConnection(1001));
        System.out.println(Arrays.toString(flowchartSys.query(103)));
        System.out.println(flowchartSys.removeNode(101));
        System.out.println(Arrays.toString(flowchartSys.query(103)));
    }
}
